<!-- src/views/UserListView.vue -->
<template>
  <div class="user-management">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <h2>用户管理</h2>
      <div class="header-actions">
        <button class="btn-primary" @click="showCreateDialog = true">
          <span>+</span> 添加用户
        </button>
        <button class="btn-secondary" @click="showRoleDialog = true">
          👥 角色管理
        </button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="filters">
      <div class="search-box">
        <input 
          v-model="searchParams.username" 
          placeholder="搜索用户名..."
          class="search-input"
          @keyup.enter="loadUsers"
        >
        <input 
          v-model="searchParams.email" 
          placeholder="搜索邮箱..."
          class="search-input"
          @keyup.enter="loadUsers"
        >
        <select v-model="searchParams.role" class="role-select">
          <option value="">全部角色</option>
          <option value="admin">管理员</option>
          <option value="teacher">教师</option>
          <option value="student">学生</option>
        </select>
        <button class="btn-search" @click="loadUsers">搜索</button>
        <button class="btn-reset" @click="resetSearch">重置</button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content-area">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <p>⏳ 正在加载用户数据...</p>
      </div>

      <!-- 用户列表表格 -->
      <div v-else class="table-container">
        <table v-if="users.length > 0" class="data-table">
          <thead>
            <tr>
              <th>ID</th>
              <th>用户名</th>
              <th>邮箱</th>
              <th>手机号</th>
              <th>角色</th>
              <th>状态</th>
              <th>创建时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="user in users" :key="user.id">
              <td>{{ user.id }}</td>
              <td>{{ user.username }}</td>
              <td>{{ user.email || '-' }}</td>
              <td>{{ user.phone || '-' }}</td>
              <td>
                <span :class="['role-badge', getRoleClass(user.role)]">
                  {{ getRoleText(user.role) }}
                </span>
              </td>
              <td>
                <span :class="['status-badge', user.status === 1 ? 'active' : 'inactive']">
                  {{ user.status === 1 ? '启用' : '禁用' }}
                </span>
              </td>
              <td>{{ formatDate(user.createTime) }}</td>
              <td>
                <button class="btn-edit" @click="editUser(user)">编辑</button>
                <button 
                  class="btn-toggle-status" 
                  @click="toggleUserStatus(user)"
                  :class="user.status === 1 ? 'btn-disable' : 'btn-enable'"
                >
                  {{ user.status === 1 ? '禁用' : '启用' }}
                </button>
                <button class="btn-assign-role" @click="assignUserRole(user)">分配角色</button>
                <button class="btn-delete" @click="deleteUser(user.id)">删除</button>
              </td>
            </tr>
          </tbody>
        </table>

        <!-- 空状态提示 -->
        <div v-else class="empty-state">
          <div class="empty-icon">👥</div>
          <p>暂无用户数据</p>
          <button class="btn-primary" @click="showCreateDialog = true">添加第一个用户</button>
        </div>
      </div>
    </div>

    <!-- 分页控件 -->
    <div v-if="pagination.total > 0" class="pagination">
      <button :disabled="pagination.current === 1" @click="prevPage">上一页</button>
      <span>第 {{ pagination.current }} 页 / 共 {{ pagination.pages }} 页 (共 {{ pagination.total }} 条记录)</span>
      <button :disabled="pagination.current === pagination.pages" @click="nextPage">下一页</button>
    </div>

    <!-- 用户模态框 -->
    <UserModal 
      v-if="showCreateDialog || editingUser"
      :user="editingUser"
      @close="closeModal"
      @saved="handleUserSaved"
    />

    <!-- 角色管理模态框 -->
    <RoleManagementModal 
      v-if="showRoleDialog"
      @close="showRoleDialog = false"
    />
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import UserModal from '@/components/UserModal.vue';
import RoleManagementModal from '@/components/RoleManagementModal.vue';
import { userApi } from '@/api/user';
import { UserQuery } from '@/models/user';

export default {
  name: 'UserListView',
  components: {
    UserModal,
    RoleManagementModal
  },
  setup() {
    const users = ref([]);
    const loading = ref(false);
    const showCreateDialog = ref(false);
    const showRoleDialog = ref(false);
    const editingUser = ref(null);
    
    const searchParams = ref(new UserQuery());
    
    const pagination = ref({
      current: 1,
      size: 10,
      total: 0,
      pages: 0
    });

    const loadUsers = async () => {
      loading.value = true;
      try {
        console.log('🚀 开始加载用户数据...', searchParams.value);
        const response = await userApi.getUsers(searchParams.value);
        console.log('📨 完整API响应:', response.data);
        
        if (response.data.code === '000000') {
          const responseData = response.data.data;
          console.log('📊 响应数据内容:', responseData);
          
          // 根据后端数据结构解析
          if (responseData && Array.isArray(responseData.data)) {
            users.value = responseData.data;
            pagination.value.total = responseData.total || 0;
            pagination.value.current = responseData.currentPage || 1;
            pagination.value.pages = Math.ceil(pagination.value.total / searchParams.value.size);
          } else if (Array.isArray(responseData)) {
            users.value = responseData;
            pagination.value.total = responseData.length;
            pagination.value.pages = 1;
          } else {
            console.warn('⚠️ 无法解析的数据结构，使用备用方案');
            users.value = getMockData();
          }
        } else {
          console.error('❌ API返回错误:', response.data.msg);
          users.value = getMockData();
        }
      } catch (error) {
        console.error('💥 加载用户列表失败:', error);
        users.value = getMockData();
      } finally {
        loading.value = false;
      }
    };

    // 模拟数据备用
    const getMockData = () => {
      return [
        {
          id: 1,
          username: 'admin',
          email: 'admin@school.com',
          phone: '13800138000',
          role: 'admin',
          status: 1,
          createTime: '2024-01-15T10:00:00'
        },
        {
          id: 2,
          username: 'teacher1',
          email: 'teacher1@school.com',
          phone: '13800138001',
          role: 'teacher',
          status: 1,
          createTime: '2024-01-16T09:00:00'
        },
        {
          id: 3,
          username: 'student1',
          email: 'student1@school.com',
          phone: '13800138002',
          role: 'student',
          status: 1,
          createTime: '2024-01-17T11:20:00'
        }
      ];
    };

    const getRoleClass = (role) => {
      const roleClasses = {
        admin: 'admin',
        teacher: 'teacher',
        student: 'student'
      };
      return roleClasses[role] || 'default';
    };

    const getRoleText = (role) => {
      const roleTexts = {
        admin: '管理员',
        teacher: '教师',
        student: '学生'
      };
      return roleTexts[role] || role;
    };

    const editUser = (user) => {
      editingUser.value = { ...user };
    };

    const deleteUser = async (id) => {
      if (confirm('确定要删除这个用户吗？此操作不可恢复。')) {
        try {
          const response = await userApi.deleteUser(id);
          if (response.data.code === '000000') {
            await loadUsers();
          } else {
            alert('删除失败: ' + response.data.msg);
          }
        } catch (error) {
          console.error('删除失败:', error);
          alert('删除失败: ' + (error.response?.data?.message || error.message));
        }
      }
    };

    const toggleUserStatus = async (user) => {
      const newStatus = user.status === 1 ? 0 : 1;
      try {
        // 立即更新本地状态
        const userIndex = users.value.findIndex(u => u.id === user.id);
        if (userIndex !== -1) {
          users.value[userIndex].status = newStatus;
        }
        
        // 使用LoginRequest格式更新状态
        const updateData = {
          username: user.username,
          status: newStatus
          // 其他字段保持不变或根据实际情况传递
        };
        
        const response = await userApi.updateUser(user.id, updateData);
        if (response.data.code === '000000') {
          console.log('✅ 用户状态更新成功');
        } else {
          throw new Error(response.data.msg);
        }
      } catch (error) {
        console.error('❌ 更新用户状态失败:', error);
        
        // 恢复原状态
        const userIndex = users.value.findIndex(u => u.id === user.id);
        if (userIndex !== -1) {
          users.value[userIndex].status = user.status;
        }
        
        const errorMsg = error.response?.data?.message || error.message || '操作失败';
        alert(`操作失败: ${errorMsg}`);
      }
    };

    const assignUserRole = (user) => {
      // 打开角色分配对话框
      alert(`分配角色功能待实现 - 用户: ${user.username}`);
    };

    const resetSearch = () => {
      searchParams.value = new UserQuery();
      loadUsers();
    };

    const closeModal = () => {
      showCreateDialog.value = false;
      editingUser.value = null;
    };

    const handleUserSaved = () => {
      closeModal();
      loadUsers();
    };

    const prevPage = () => {
      if (searchParams.value.current > 1) {
        searchParams.value.current--;
        loadUsers();
      }
    };

    const nextPage = () => {
      if (searchParams.value.current < pagination.value.pages) {
        searchParams.value.current++;
        loadUsers();
      }
    };

    const formatDate = (dateString) => {
      if (!dateString) return '-';
      try {
        return new Date(dateString).toLocaleDateString();
      } catch (error) {
        return dateString;
      }
    };

    onMounted(() => {
      console.log('📍 UserListView组件已挂载');
      loadUsers();
    });

    return {
      users,
      loading,
      searchParams,
      pagination,
      showCreateDialog,
      showRoleDialog,
      editingUser,
      loadUsers,
      getRoleClass,
      getRoleText,
      editUser,
      deleteUser,
      toggleUserStatus,
      assignUserRole,
      resetSearch,
      closeModal,
      handleUserSaved,
      prevPage,
      nextPage,
      formatDate
    };
  }
};
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filters {
  margin-bottom: 20px;
}

.search-box {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input, .role-select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  min-width: 150px;
}

.btn-primary, .btn-secondary, .btn-search, .btn-reset {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.btn-primary {
  background-color: #3498db;
  color: white;
}

.btn-secondary {
  background-color: #9b59b6;
  color: white;
}

.btn-search {
  background-color: #2ecc71;
  color: white;
}

.btn-reset {
  background-color: #95a5a6;
  color: white;
}

.main-content-area {
  min-height: 400px;
}

.loading-state {
  text-align: center;
  padding: 40px;
  color: #666;
}

.table-container {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.data-table th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #2c3e50;
}

.role-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.role-badge.admin {
  background: #e3f2fd;
  color: #1565c0;
}

.role-badge.teacher {
  background: #f3e5f5;
  color: #7b1fa2;
}

.role-badge.student {
  background: #e8f5e9;
  color: #2e7d32;
}

.role-badge.default {
  background: #f5f5f5;
  color: #616161;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.active {
  background: #e8f5e9;
  color: #2e7d32;
}

.status-badge.inactive {
  background: #ffebee;
  color: #d32f2f;
}

.btn-edit, .btn-delete, .btn-toggle-status, .btn-assign-role {
  padding: 6px 12px;
  margin: 0 2px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.btn-edit {
  background-color: #ff9800;
  color: white;
}

.btn-delete {
  background-color: #f44336;
  color: white;
}

.btn-assign-role {
  background-color: #9c27b0;
  color: white;
}

.btn-enable {
  background-color: #4caf50;
  color: white;
}

.btn-disable {
  background-color: #9e9e9e;
  color: white;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #666;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
}

.pagination button {
  padding: 8px 16px;
  border: 1px solid #ddd;
  background: white;
  cursor: pointer;
  border-radius: 4px;
}

.pagination button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>